Skip to content

Exercises

Gradient generator

Let's keep working on our gradient generator tool! Instead of limiting the user to 2 colors, we'll let them add up to 5 colors.

Acceptance Criteria:

  • The color inputs should work; picking a new color should update the gradient accordingly.
  • Clicking “Add color” should add a new color, at the end of the array.
  • Clicking "Remove color" should remove the last color in the array.
  • When adding new colors, they should default to #FF0000 (bright red).
  • There should always be between 2 and 5 colors. No more, no less.

Code Playground

import React from 'react';
function App() {
const [colors, setColors] = React.useState([
'#FFD500',
'#FF0040',
]);
const colorStops = colors.join(', ');
const backgroundImage = `linear-gradient(${colorStops})`;

return (
<div className="wrapper">
<div className="actions">
<button>
Remove color
</button>
<button>
Add color
</button>
</div>
<div
className="gradient-preview"
style={{
backgroundImage,
}}
/>
<div className="colors">
{colors.map((color, index) => {
const colorId = `color-${index}`;
return (
<div key={colorId} className="color-wrapper">
<label htmlFor={colorId}>
Color {index + 1}:
</label>
<div className="input-wrapper">
<input
id={colorId}
type="color"
/>
</div>
</div>
);
})}
</div>
</div>
);
}

export default App;

Solution:

Stretch Goal

When the user removes and then re-adds a color, it should be restored to the previously-set value, rather than being reset to #FF0000.

Here's an example. Notice how the blue and green colors are "remembered", instead of being re-added as bright red:

If your solution already works this way, you're done! But I suspect most students will need to make some pretty substantial tweaks to implement this new requirement.

You can continue working in the sandbox above. Also, we cover some very interesting ground in the “stretch” solution video below, so be sure to check it out!

Stretch goal solution: